<?php
namespace Views;
/**
 * File holds class for generating businesses view
 *
 * PHP version 5.3.5
 *
 * @category   CM
 * @package    Views
 * @subpackage -
 * @author     markus karileet <markuskarileet@hotmail.com>
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL
 * @link       -
 */
class Business extends Page {
	private $_service;
	
	public function __construct($language) {
		$this->setUp($language, 0);
		$this->_service = new \Services\Business();
	}
	
	/**
	 * Method shows top businesses. Businesses are ordered by Net Promoter score
	 * @param int $type Type ID
	 */
	public function viewTopBusinesses($type = 0) {
		//read category businesses 
		$object = new \Entities\Business();
		$object->setType($type);
		$npsArray = array();
		$businesses = $this->_service->selectMulti($object);
		$feedbackService = new \Services\Feedback();
		$fb = new \Entities\Feedback();
		if (count($businesses) > 0 && $businesses) {
			foreach (array_keys($businesses) as $key) {
				//read ratings and generate NPS
				$fb->setBusiness($businesses[$key]->getId());
				$ratings = $feedbackService->selectMulti($fb);
				if ($ratings) {
					$nps = $this->_service->calculateNps($ratings);
				} else {
					$nps = 0;
				}
				$npsArray[$key] = $nps;
			}
		}
		$this->_smarty->assign('businessArray', $businesses);
		arsort($npsArray);
		$this->_smarty->assign('npsArray', $npsArray);
		$this->_content = $this->_smarty->fetch('topBusinesses.tpl');
		$this->display();
	}
	
	/**
	 * Method shows business details page
	 * @param int $id Business ID
	 */
	public function viewBusinessDetails($id) {
		$object = new \Entities\Business();
		$object->setId($id);
		$business = $this->_service->select($object);
		$feedbackService = new \Services\Feedback();
		$fb = new \Entities\Feedback();
		$fb->setBusiness($business->getId());
		$ratings = $feedbackService->selectMulti($fb);
		if ($ratings) {
			$nps = $this->_service->calculateNps($ratings);
		} else {
			$nps = 0;
		}
		$this->_smarty->assign('nps', $nps);
		$this->_smarty->assign('business', $business);
		$this->_smarty->assign('feedbacks', $ratings);
		$this->_content = $this->_smarty->fetch('companyDetails.tpl');
		$this->display();
	}
	
	/**
	 * Method shows my company comments and scores page
	 */
	public function viewMyScoresAndComments($id) {
		$object = new \Entities\Business();
		$object->setId($id);
		$business = $this->_service->select($object);
		$feedbackService = new \Services\Feedback();
		$fb = new \Entities\Feedback();
		$fb->setBusiness($business->getId());
		$ratings = $feedbackService->selectMulti($fb);
		if ($ratings) {
			$nps = $this->_service->calculateNps($ratings);
		} else {
			$nps = 0;
			//assign empty array to ratings for template. if this is null-length
			//array, i can use foreachelse to show that nothing was found
			$ratings = array();
		}
		$this->_smarty->assign('nps', $nps);
		$this->_smarty->assign('business', $business);
		$this->_smarty->assign('feedbacks', $ratings);
		$this->_content = $this->_smarty->fetch('commentsAndScores.tpl');
		$this->display();
	}
	
	/**
	 * Method to show comments and scores via ajax request for comments and scores page
	 * @param array $post HTTP POST
	 * @return var Template string for html injection
	 */
	public function viewCommentSearchResults($post) {
		$fbService = new \Services\Feedback();
		$feedbacks = $fbService->commentSearch($post['detractors'], $post['passives'], $post['promoters'], $post['fromdate'], $post['todate'], 4);
		if (!$feedbacks) {
			$feedbacks = array();
		}
		$this->_smarty->assign('feedbacks', $feedbacks);
		return $this->_smarty->fetch('myFeedback.tpl');
	}
	
	/**
	 * Method generates analytics PNG according to input parameters.
	 * Called via ajax
	 * @param array $post HTTP POST array
	 */
	public function viewAnalyticsSearchResults($post) {
		//get feedbacks from period and get NPS array
		$feedbacks = array();
		$score = array();
		$fbService = new \Services\Feedback();
		//read feedback for range.
		$feedbacks = $fbService->commentSearch(0, 0, 0, $post['start'], $post['end'], $post['business']);
		//determine step (day, week etc), DAY for now..
		$start = strtotime($post['start']);
		$end = strtotime($post['end']);
		for ($i = $start; $i < ($end + 1); $i = strtotime('+1 day', $i)) {
			$group = array();
			foreach ($feedbacks as $fb) {
				//group comments by time
				if ($fb->getTime() >= $i && $fb->getTime() <= ($i + 86400)) {
					$group[] = $fb;
				}
			}
			//calculate NPS
			if (count($group) > 0) {
				$score[date('d.m', $i)] = $this->_service->calculateNps($group);
			} else {
				$score[date('d.m', $i)] = 0;
			}
		}
		$object = new \Entities\Business();
		$object->setId($post['business']);
		$object = $this->_service->select($object);
		$this->generatePngChart($score, $object->getCode());
	}
	
	/**
	 * Method shows company analytics view
	 * @param int $id Company ID
	 */
	public function viewMyAnalytics($id) {
		$object = new \Entities\Business();
		$object->setId($id);
		$business = $this->_service->select($object);
		$this->_smarty->assign('business', $business);
        //show last week by default
		$this->viewAnalyticsSearchResults(array('business' => $id, 'start' => date('d.m.Y', strtotime('-1 week')), 'end' => date('d.m.Y')));
		$this->_content = $this->_smarty->fetch('companyAnalytics.tpl');
		$this->display();
	}
	
	/**
	 * Method generates PNG chart from $input
	 * @param array $input array like array(xAxisVal => pointVal)
	 * @param var Business code
	 */
	public function generatePngChart($input, $businessCode) {
		// Standard inclusions
		include(APPPATH . "lib/pChart/pData.class");
		include(APPPATH . "lib/pChart/pChart.class");
		
		// Dataset definition
		$DataSet = new \pData;
		
		foreach($input as $week => $val) {
			$DataSet->AddPoint($val, "Serie1", $week);
		}
		$DataSet->AddAllSeries();
		$DataSet->SetAbsciseLabelSerie();
		$DataSet->SetSerieName("NPS","Serie1");
		
		// Initialise the graph
		$Test = new \pChart(750,400);
		$Test->setFontProperties(APPPATH . "tmp/tahoma.ttf",8);
		$Test->setGraphArea(70,30,730,370);
		$Test->drawGraphArea(255,255,255,TRUE);
		$Test->drawScale($DataSet->GetData(),$DataSet->GetDataDescription(),7,150,150,150,TRUE,0,0);
		$Test->drawGrid(4,TRUE,230,230,230,50);
		
		// Draw the 0 line
		$Test->setFontProperties(APPPATH . "tmp/tahoma.ttf",6);
		$Test->drawTreshold(0,143,55,72,TRUE,TRUE);
		
		// Draw the line graph
		$Test->drawLineGraph($DataSet->GetData(),$DataSet->GetDataDescription());
		$Test->drawPlotGraph($DataSet->GetData(),$DataSet->GetDataDescription(),3,2,255,255,255);
		
		// Finish the graph
		$Test->setFontProperties(APPPATH . "tmp/tahoma.ttf",8);
		$Test->drawLegend(75,35,$DataSet->GetDataDescription(),255,255,255);
		$Test->setFontProperties(APPPATH . "tmp/tahoma.ttf",10);
		$Test->drawTitle(60,22,"Net Promoter Scores",50,50,50,585);
		$Test->Render(APPPATH.'tmp/'.$businessCode.'.png'); 
		 
	}
}